package com.example.common.base;

import com.example.common.dialog.LoadingDialog;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;

/**
 * @author geyao
 * @date 2021/7/6
 * des:
 */
public abstract class UseCase<T> {
    private LoadingDialog loadingDialog;
    private final TaskDispatcher globalTaskDispatcher;
    private final TaskDispatcher uiTaskDispatcher;

    public UseCase(Context context, boolean isShowProgress) {
        globalTaskDispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        uiTaskDispatcher = context.getUITaskDispatcher();
        if (isShowProgress) {
            loadingDialog = new LoadingDialog(context);
        }
    }

    public abstract void buildWork(INetCallBack<T> callBack);

    public void execute(INetCallBack<T> callBack) {
        showLoading();
        globalTaskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                buildWork(new INetCallBack<T>() {
                    @Override
                    public void onNext(T t) {
                        uiTaskDispatcher.syncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                hideLoading();
                                callBack.onNext(t);
                            }
                        });
                    }

                    @Override
                    public void onError(Exception exception) {
                        uiTaskDispatcher.syncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                hideLoading();
                                callBack.onError(exception);
                            }
                        });
                    }
                });
            }
        });
    }

    public void showLoading() {
        if (loadingDialog != null && !loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    public void hideLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.hide();
        }
    }
}
